package com.chx.rpc05;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

public class Stub{

    private static String clazzName=null;

    public static Object getStub(Class clazz){
        clazzName=clazz.getName();
        InvocationHandler h = new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Socket socket = new Socket("localhost", 8080);
                OutputStream os = socket.getOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(os);
                oos.writeUTF(clazzName);
                oos.writeUTF(method.getName());
                oos.writeObject(method.getParameterTypes());
                oos.writeObject(args);
                oos.flush();

                InputStream is=socket.getInputStream();
                ObjectInputStream ois = new ObjectInputStream(is);
                Object object = ois.readObject();
                return object;
            }
        };
        Object o = Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), h);
        return o;
    }
}
